<template>
	<el-dialog :title="title" v-model="open" append-to-body :close-on-click-modal="false" width="600px">
		<el-upload
			ref="formRef"
			:limit="1"
			accept=".xlsx, .xls"
			:headers="headers"
			:action="uploadDeliveryUrl"
			:disabled="isUploading"
			:on-progress="onFileUploadProgress"
			:on-success="onFileSuccess"
			:auto-upload="false"
			drag
		>
			<i class="el-icon-upload"></i>
			<div class="el-upload__text">
				将文件拖到此处，或
				<em>点击上传</em>
			</div>
			<template #tip>
				<div class="el-upload__tip" style="color: red">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
			</template>
		</el-upload>
		<template #footer>
			<div class="dialog-footer">
				<el-button type="primary" :loading="submitLoading" @click="onSubmitForm">确定</el-button>
				<el-button @click="onCancel">取消</el-button>
			</div>
		</template>
	</el-dialog>
</template>

<script lang="ts">
import { reactive, ref, toRefs } from 'vue';
import { ElMessage } from 'element-plus';

import { Session } from '/@/utils/storage';

export default {
	name: 'goodImportDialog',
	setup() {
		const state = reactive({
			title: '批量商品导入',
			open: false,
			uploadDeliveryUrl: `${import.meta.env.VITE_API_URL}/admin/goods_import`,
			headers: {
				token: Session.get('token'),
			},
			isUploading: false, // 是否禁用上传
			submitLoading: false,
		});

		const formRef = ref(null);
		let callback: Function = () => {};

		/********** 点击事件(on开头) **********/
		// 文件上传中处理
		const onFileUploadProgress = () => {
			state.isUploading = true;
		};
		// 文件上传成功处理
		const onFileSuccess = (res: any) => {
			console.log('res', res);

			state.open = false;
			state.isUploading = false;
			(formRef.value as any)?.clearFiles();
			ElMessage.success('操作成功');
			callback();
		};
		/** 提交按钮 */
		const onSubmitForm = () => {
			(formRef.value as any)?.submit();
			onCancel();
		};
		// 取消按钮
		const onCancel = () => {
			state.submitLoading = false;
			state.open = false;
		};

		/********** 方法事件 **********/
		//打开
		const openDialog = (config: any, fn: Function) => {
			console.log(config);
			callback = fn;
			state.open = true;
		};

		return {
			formRef,
			onFileUploadProgress,
			onFileSuccess,
			onSubmitForm,
			openDialog,
			onCancel,
			...toRefs(state),
		};
	},
};
</script>

<style lang="scss" scoped></style>
